import React, { FC, useState } from 'react';
import ReactDOM from 'react-dom';
import { Modal, Form, Input, Button, Alert } from 'antd';
import { login } from './service';
import EventEmitter from 'events';

import { Provider } from 'mobx-react';
import stores from '../../stores';
import { UserInfo } from '@/stores/modules/userInfo';
import { observer, inject } from 'mobx-react';

const ee = new EventEmitter();

export interface ILoginModalProps {
  visible: boolean;
  onCancel: () => void;
  userInfoStore?: any;
}

const LoginModal: FC<ILoginModalProps> = inject('userInfoStore')(
  observer((props) => {
    console.log('LoginModal props', props);
    const [form] = Form.useForm();
    const { visible = false, onCancel } = props;
    const [errorText, setErrorText] = useState('');

    async function onFinish(values: any) {
      const res = await login({
        data: values,
        errorHandler: (e) => {
          setErrorText(e.message);
        },
      });
      const { code, data } = res;
      if (code === 0) {
        const info: UserInfo = { name: data.loginName, id: data.userId };
        props.userInfoStore.setUserInfo(info);
        ee.emit('resolveCallback', 1);
      }
    }

    function onFinishFailed(aa: any) {}

    function afterAlertClose() {
      setErrorText('');
    }

    return (
      <Modal
        title="请登录"
        centered
        visible={visible}
        // onOk={() => setModalVisible(false)}
        onCancel={() => onCancel()}
        maskClosable={false}
        closeIcon={null}
        footer={null}
        destroyOnClose={true}
        getContainer={document.getElementById('__login_modal')}
        width={360}
        bodyStyle={{ padding: 0 }}
      >
        {errorText ? (
          <Alert
            message={errorText}
            afterClose={afterAlertClose}
            type="error"
            closable
            banner
            showIcon={false}
          />
        ) : null}
        <div style={{ padding: '24px' }}>
          <Form
            name="basic"
            form={form}
            initialValues={{
              username: '',
              password: '',
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入账号' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item>
              <Button htmlType="submit" type="primary" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Modal>
    );
  }),
);

const identification = {
  showModal: () => {
    return new Promise((resolve) => {
      ee.on('resolveCallback', (code) => {
        resolve(code);
      });

      const loginModalDom = document.getElementById('__login_modal');
      // 只弹出一个登录框
      if (!loginModalDom) {
        const div = document.createElement('div');
        div.id = '__login_modal';
        document.body.appendChild(div);

        ReactDOM.render(
          <Provider {...stores}>
            <LoginModal visible={true} onCancel={identification.removeModal} />
          </Provider>,
          div,
        );
      }
    });
  },
  removeModal: () => {
    const loginModalDom = document.getElementById('__login_modal');
    if (loginModalDom) {
      loginModalDom.remove();
    }
    ee.emit('resolveCallback', 0);
  },
};

export default identification;
